package com.xzy.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 通过Holder获取
 *
 * @author xzy.xiao
 * @date 2023/11/13  20:07
 */
@Slf4j
@RestController
@RequestMapping("/bbb")
public class BbbController {

    @RequestMapping("/test1")
    public void test1() {
        HttpServletRequest httpServletRequest = getHttpServletRequest();

    }

    @RequestMapping("/test2")
    public void test2() {
        HttpServletRequest httpServletRequest = getHttpServletRequest();
    }

    @RequestMapping("/test3")
    public void test3() {
        HttpServletRequest httpServletRequest = getHttpServletRequest();
    }

    private HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            throw new RuntimeException();
        }

        return servletRequestAttributes.getRequest();
    }
}
